#include "qrcode.h"
#include "qrcode_p.h"

#include "qmlmanager.h"
#include "qmlobject.h"
#include <QDebug>
#include <QQmlContext>
#include <QQmlEngine>
#include <QtQml>
#include <SyberosGuiCache>
//#include <QObject>
#include <QQuickView>
#include "qrcoderegister.h"

using namespace NativeSdk;

Qrcode::Qrcode()
{
    qDebug() <<Q_FUNC_INFO<<", Qrcode create";
    d = new QrcodePrivate();
}

Qrcode::~Qrcode()
{
    qDebug() <<Q_FUNC_INFO<<", Qrcode destroyed";
    delete d;
}

void Qrcode::invokeInitialize()
{
    qmlRegisterType<DecodeWorkSpace>("com.syberos.decodeWorkSpace", 1, 0, "DecodeWorkSpace");
}

void Qrcode::initview() {
    QQuickView *m_view = SYBEROS::SyberosGuiCache::qQuickView();

    QtCamera::destroyInstance();
    QtCamera *camera = QtCamera::getInstance();
    qDebug() << "initview:" << camera;
    QQmlEngine::setObjectOwnership(camera, QQmlEngine::CppOwnership);
    m_view->rootContext()->setContextProperty("QtCamera", camera);
}

void Qrcode::invoke(const QString &callbackID, const QString &action, const QVariantMap &params)
{
    Q_UNUSED(params)

    if(action == "scan"){
        initview();
        scan(callbackID);
    }
    else{
        qDebug() << "unknown this action";
    }
}

void Qrcode::decodeFinished(const QString &decodeContent)
{
    qDebug() <<Q_FUNC_INFO<<", params:" << decodeContent;
    QJsonObject json;
    json.insert("result", decodeContent);
    signalManager()->success(d->callbackID.toLong(), json);
}

void Qrcode::cancel()
{
    signalManager()->success(d->callbackID.toLong(), QVariant());
}

void Qrcode::scan(const QString &callbackID)
{
    d->callbackID = callbackID;

    QmlManager manager;

    d->qmlObject = manager.open("qrc:/qml/BarCodeScan.qml");

    manager.connectSignal(d->qmlObject, SIGNAL(decodeFinished(QString)), this, SLOT(decodeFinished(QString)));
    manager.connectSignal(d->qmlObject, SIGNAL(cancel()), this, SLOT(cancel()));
}

